﻿using System;
using System.Text;

namespace OWA2SMTP
{
  class Program
  {
    private static System.IO.StreamWriter streamWriter;

    static void Main(string[] args)
    {
      try
      {
        if (Properties.Settings.Default.LogToFile)
        {
          streamWriter = System.IO.File.AppendText("Log.txt");
        }

        ShowMessage("{0} v{1} starting ({2})...", System.Reflection.Assembly.GetEntryAssembly().GetName().Name, System.Reflection.Assembly.GetEntryAssembly().GetName().Version, System.DateTime.Now.ToLongTimeString());
        MessageDownloader messageDownloader = new MessageDownloader(Properties.Settings.Default.URL, Properties.Settings.Default.Username, Properties.Settings.Default.Password);
        ShowMessage("   {0} e-mails found ({1} unread)", messageDownloader.messageInfos.Count, messageDownloader.unreadMessages.Count);
        //messageDownloader.DownloadAllMessages();
        messageDownloader.DownloadUnreadMessages();
        ShowMessage("   {0} e-mails downloaded", messageDownloader.downloadedMessages.Count);

        MessageSender messageSender = new MessageSender(Properties.Settings.Default.SMTPServer, Properties.Settings.Default.FromAddress, Properties.Settings.Default.ToAddress);
        foreach (Message message in messageDownloader.downloadedMessages)
        {
          StringBuilder mailBody = new StringBuilder();
          mailBody.AppendLine("From: " + message.From);
          mailBody.AppendLine("Sent: " + message.Sent.ToLongDateString() + " " + message.Sent.ToLongTimeString());
          mailBody.AppendLine("To: " + message.To);
          mailBody.AppendLine("Subject: " + message.Subject);
          mailBody.AppendLine("===================");
          mailBody.Append(message.Body);

          messageSender.SendEmail(message.Subject, mailBody.ToString());
        }

        ShowMessage("   Saving extracted message IDs to MessageIDs.xml");
        messageDownloader.SerializeMessageIDs("MessageIDs.xml");

        ShowMessage("   Saving extracted messages to Messages.xml");
        messageDownloader.SerializeMessages("Messages.xml");
      }
      catch (Exception ex)
      {
        ShowMessage("   ! Fatal error: {0}", ex.Message);
      }
      finally
      {
        ShowMessage("...{0} finished ({1})", System.Reflection.Assembly.GetEntryAssembly().GetName().Name, System.DateTime.Now.ToLongTimeString());
        if (streamWriter != null)
        {
          streamWriter.Close();
        }
      }
    }

    public static void ShowMessage(string message, params object[] strings)
    {
      try
      {
        Console.WriteLine(string.Format(message, strings));
        if (streamWriter != null)
        {
          streamWriter.WriteLine(string.Format(message, strings));
        }
      }
      catch { }
    }
  }
}